<?php
//支付宝手机网站支付 回调地址
// 授权回调地址，将用户的UID与授权返回码存入

/*1、连接数据库 
        端口号或者地址 
        登录数据库的登录名
        登录密码
        要操作的数据库名
        */


if ($_POST) {
    $val = '---------------------POST异步通知----------------<br>';
    $val .= json_encode($_POST);
    $val .= $update;
    $val .= '-------------------------------------------------<br>';
} else {
    $val = '------------------------GET通知-------------------<br>';
    $val .= json_encode($_GET);
    $val .= '-------------------------------------------------<br>';
}

file_put_contents("shouji.txt", $val . PHP_EOL, FILE_APPEND);

$link = mysqli_connect('127.0.0.1', 'ali', 'ali', 'ali', '3306');
if (!$link) {

}

//2、选择要操作的数据库
mysqli_select_db($link, 'ali');
//3、设置交互编码
mysqli_query($link, 'set names utf8');


// 高级支付高级支付高级支付高级支付高级支付


if ($_POST['trade_status'] == 'TRADE_SUCCESS') {//交易成功
    // 保存数据操作 1、将订单状态修改为成功；2、修改平台用户的余额；


    // 1、将订单状态修改为成功
    $danhao = $_POST['out_trade_no'];

    $select = "select * from `jd_dingdan` where `danhao`='{$danhao}' limit 1";
    // $select="select * from `jd_kbsh` where `uid`=222";
    $arr = mysqli_query($link, $select);
    $one = mysqli_fetch_assoc($arr);

    if ($one['status'] == 1) {
        file_put_contents("xykResult.txt", '订单状态已修改' . PHP_EOL, FILE_APPEND);

    } else {
        $trade_no = $_POST['trade_no'];
        $buyer = $_POST['buyer_logon_id'];
        $seller = $_POST['seller_email'];
        $money = $_POST['total_amount'];
        $buyer_id = $_POST['buyer_id'];
        // gather
        $uid = $one['uid'];
        $select = "select * from `jd_gather` where `uid`={$uid} limit 1";

        $arr = mysqli_query($link, $select);
        $_one = mysqli_fetch_assoc($arr); //用户

        if ($one['hk'] == 1) {//不回款--手动
            $yh_money = $money * (100 - $_one['up_set2']) / 100;
        } else {
            //用户订单收益 = 订单金额 × （回款费率 - 上级设定费率）
	    	$yh_money   =$money*($_one['path5']-$_one['up_set2'])/100; //回款



        }

        $total = $_one['money'] + $yh_money;
        $update = "update `jd_dingdan` set `trade_no`='{$trade_no}',`buyer`='{$buyer}',`seller`='{$seller}',`status`=1,`pay_money`={$money},`yh_money`='{$yh_money}' where `danhao`='{$danhao}'";

        $id = mysqli_query($link, $update);

        if ($id > 0) {
            file_put_contents("xykResult.txt", '订单状态修改成功' . PHP_EOL, FILE_APPEND);

            // 2、修改平台用户的余额；
            // $select="select * from `jd_dingdan` where `danhao`='{$danhao}' limit 1";
            // // $select="select * from `jd_kbsh` where `uid`=222";
            // $arr=mysqli_query($link,$select);
            // $one=mysqli_fetch_assoc($arr);
            // 判断是否要回款 不回款的用户余额=总*(1-费率)/100 -2
            $update = "update `jd_dingdan` set `t_money`='{$total}' where `danhao`='{$danhao}'";

            mysqli_query($link, $update);


            // 修改平台用户余额
            $update = "update `jd_gather` set `money`={$total} where `uid`={$uid}";
            $re = mysqli_query($link, $update);
            if ($re > 0) {
                file_put_contents("xykResult.txt", '平台用户余额修改成功' . PHP_EOL, FILE_APPEND);

                if ($one['hk'] == 1) {
                    //不回款不需制定
                } else {
                    // 插播：制定对应的回款表
                    $trans_money = $money * (1 - $_one['path5'] / 100);
                    //回款金额 = 订单金额 ×（100- 回款费率）

                    $out_biz_no = 'xy' . date("YmdHis") . rand(1000, 9999);
                    $add = "insert into `jd_trans` (`trade_no`,`uid`,`money`,`buyer_id`,`out_biz_no`) values ('{$trade_no}','{$uid}','{$trans_money}','{$buyer_id}','{$out_biz_no}')";
                    $trans_result = mysqli_query($link, $add);
                    if($trans_result){

                        file_put_contents("xykResult.txt", '回款表写入成功' . PHP_EOL, FILE_APPEND);
                    }else{
                        file_put_contents("xykResult.txt", '回款表写入失败' . PHP_EOL, FILE_APPEND);
                    }
                }
                // echo success;
                // 4、查询是否有上级 有的话需要给上级的余额增加该笔订单的%
                $select = "select * from `jd_ptyh` where `uid`={$one[uid]} limit 1";
                $arr = mysqli_query($link, $select);
                $one2 = mysqli_fetch_assoc($arr);  //当前用户

                if ($one2['pid'] == 0 || $one2['level'] > 6) {//没有上级+4级以下
                    echo success;
                } else {
                    // 查找上一级
                    /** 父级 start */
                    $select = "select * from `jd_ptyh` where `uid`={$one2[pid]} limit 1";
                    $arr = mysqli_query($link, $select);
                    $one3 = mysqli_fetch_assoc($arr);  //当前用户的上级
                    $shou = $one['uid'];
                    $parent = $one3['uid'];
                    $danhao = 'xy' . date("YmdHis") . rand(1000, 9999);
                    $add = "insert into `jd_dividend` (`uid`,`danhao`,`trade_no`,`shou`,`parent`,`total`,`type`,`level`) values ('{$parent}','{$danhao}','{$trade_no}','{$shou}','{$parent}','{$money}',2,1)";
                    $id4 = mysqli_query($link, $add);
                    //每笔信用卡订单给父级提0.5
                    $fatherticheng = "insert into `jd_dividend` (`uid`,`danhao`,`trade_no`,`shou`,`parent`,`total`,`type`,`level`) values ('{$parent}','{$danhao}','{$trade_no}','{$shou}','{$parent}','0.5',3,1)";
                    mysqli_query($link, $fatherticheng);
                    /** 父级 end */

                    /** 爷爷级  start */
                    $grandfatherSql = "select * from `jd_ptyh` WHERE `uid` = {$one3[pid]} limit 1";
                    $grandfatherArr = mysqli_query($link, $grandfatherSql);
                    $grandfather = mysqli_fetch_assoc($grandfatherArr);
                    $grandfatherUid = $grandfather['uid'];
                    $grandfatherDividend = "insert into `jd_dividend` (`uid`,`danhao`,`trade_no`,`shou`,`parent`,`total`,`type`,`level`) values ('{$parent}','{$danhao}','{$trade_no}','{$shou}','{$parent}','{$money}',2,2)";
                    $grandfatherResult = mysqli_query($link, $grandfatherDividend);
                    //每笔信用卡订单给爷爷提成0.5
                    $grandfatherticheng = "insert into `jd_dividend` (`uid`,`danhao`,`trade_no`,`shou`,`parent`,`total`,`type`,`level`) values ('{$parent}','{$danhao}','{$trade_no}','{$shou}','{$parent}','0.5',3,2)";
                    mysqli_query($link, $grandfatherticheng);

                    /** 爷爷级 end */

                    if ($id4 > 0 && $grandfatherResult > 0) {

                        echo success;
                    } else {
                        echo fail;
                    }

                }
            } else {
                file_put_contents("xykResult.txt", '平台用户余额修改失败' . PHP_EOL, FILE_APPEND);
                echo fail;
            }

        } else {
            file_put_contents("xykResult.txt", '订单状态修改失败' . PHP_EOL, FILE_APPEND);
            echo fail;
        }


        /*
        {"gmt_create":"2017-12-11 09:50:03",
        "charset":"UTF-8",
        "seller_email":"nnxxkj007@126.com",
        "subject":"\u6709\u95f4\u5c0f\u5e97",
        "sign":"WkS\/pxdee6z127qutpve8Dw5NhZFs4llrPcmVcx2G2m39K7ya762qHU+5l84tC44rxhWokb6KTNNttcnlvDa4VLHb5mqTPgDcXAKkqWkzKiJkwHbI5hrNNqG1QkHV1IGkRkHwViju4ywz8ot9kMh3wm5C4es0csfb9tcVJJryl8=",
        "buyer_id":"2088312387000015",
        "invoice_amount":"0.10",
        "notify_id":"f4c3330419b6b959aa8486b8909a546g2x",

        "fund_bill_list":"[{\"amount\":\"0.10\",
                            \"fundChannel\":\"ALIPAYACCOUNT\"
                          }]",
        "notify_type":"trade_status_sync",
        "trade_status":"TRADE_SUCCESS",
        "receipt_amount":"0.10",
        "buyer_pay_amount":"0.10",
        "app_id":"2017060107400865",
        "sign_type":"RSA",
        "seller_id":"2088621910829161",
        "gmt_payment":"2017-12-11 09:50:03",
        "notify_time":"2017-12-11 09:50:03",
        "version":"1.0",
        "out_trade_no":"20171211094828311648",
        "total_amount":"0.10",
        "trade_no":"2017121121001004010541601561",
        "auth_app_id":"2017060107400865",
        "buyer_logon_id":"173****3411",
        "point_amount":"0.00"}

        */


    }


}



